//
//  AddressViewController.m
//  Address
//
//  Created by 胡岩 on 16/2/24.
//  Copyright © 2016年 MagicalYan. All rights reserved.
//

#import "AddressViewController.h"

#import "AddressView.h"
#import <CoreLocation/CoreLocation.h>


@interface AddressViewController ()<UITableViewDelegate, UITableViewDataSource, AddressViewDelegate, CLLocationManagerDelegate, UISearchBarDelegate>

@property (nonatomic, strong) CLLocationManager * locationManager;

@property (nonatomic, strong) NSMutableDictionary *cityDic;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *names;

@property (nonatomic, strong) AddressView *addressView;

@property (nonatomic, copy) Block block;

@property (nonatomic, strong) NSMutableArray *hotCity;

@property (nonatomic, strong) UILabel *name;

@property (nonatomic, strong) UILabel *label;

@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) NSMutableArray *tempArray;

@property (nonatomic, strong) NSMutableDictionary *tempDic;

@property (nonatomic, assign) BOOL isSearching;

@end


@implementation AddressViewController

- (instancetype)initWithBlock:(Block)block
{
    self = [super init];
    if (self) {
        _block = block;
        _cityDic = [NSMutableDictionary dictionary];
        _names = [NSMutableArray array];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(5 , 0, 100, 30)];
    _searchBar.delegate = self;
    for (UIView *view in _searchBar.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
    }
    _searchBar.backgroundColor = [UIColor clearColor];
    _searchBar.placeholder = @"输入城市名查询";
    
    self.navigationItem.titleView = _searchBar;
    _isSearching = NO;
    
    [self sonThread];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    if (searchBar.tag == 1) {
        searchBar.tag = 0;
        return NO;
    }
    [self setIsSearching:YES];
//    [searchBar setShowsCancelButton:YES animated:YES];
    return  YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *pinyin = [self transformToPinyin:[searchBar.text substringToIndex:1]];
    if ([[searchBar.text substringFromIndex:1] isEqualToString:@"长"]) {
        pinyin = @"C";
    }
    [_names removeAllObjects];
    [_cityDic removeAllObjects];
    NSMutableArray *result = [NSMutableArray array];
    for (NSString *str in _tempArray) {
        NSArray *array = [_tempDic objectForKey:str];
        for (CityModel *model in array) {
            if ([model.cityname rangeOfString:searchBar.text].location != NSNotFound) {
                if ([_cityDic objectForKey:str]) {
                    if ([str isEqualToString:@"长"]) {
                        NSMutableArray *array = [_cityDic objectForKey:@"C"];
                        [array addObject:model];
                    } else {
                        NSMutableArray *array = [_cityDic objectForKey:str];
                        [array addObject:model];
                    }
                } else {
                    NSMutableArray *array = [NSMutableArray array];
                    [array addObject:model];
                    [_cityDic setObject:array forKey:str];
                    [result addObject:str];
                }
            }
        }
    }
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
    NSWidthInsensitiveSearch | NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    [_names addObjectsFromArray:[result sortedArrayUsingComparator:sort]];
    [_tableView reloadData];
}



- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchBar.text.length == 0) {
        [self setIsSearching:NO];
        [self backToMainAddress];
        [searchBar resignFirstResponder];
        searchBar.tag = 1;
        _searchBar.text = @"";
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//    [_searchBar setShowsCancelButton:NO animated:YES];
    [searchBar backgroundImage];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_searchBar resignFirstResponder];
}


- (void)backToMainAddress {
    if (_tempArray.count > 0) {
        _names = [NSMutableArray arrayWithArray:_tempArray];
        _cityDic = [NSMutableDictionary dictionaryWithDictionary:_tempDic];
        [_tableView reloadData];
    }
}

- (void)setIsSearching:(BOOL)isSearching {
    _isSearching = isSearching;
    if (_isSearching) {
        _addressView.userInteractionEnabled = NO;
    } else {
        [_searchBar setShowsCancelButton:NO animated:YES];
        _addressView.userInteractionEnabled = YES;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSArray *array = [_cityDic  objectForKey:[NSString stringWithFormat:@"%@", _names[indexPath.section]]];
    CityModel *model = array[indexPath.row];
    cell.textLabel.text = model.cityname;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _names.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *array = [_cityDic objectForKey:[NSString stringWithFormat:@"%@", _names[section]]];
    return array.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 20, 30)];
    label.backgroundColor = [UIColor colorWithRed:214 / 255.0 green:214 / 255.0 blue:214 / 255.0 alpha:1];
    label.text = [NSString stringWithFormat:@"   %@", _names[section]];
    if ([_names[section] isEqualToString:@"#"]) {
        label.text = @"   热门城市";
    }
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isSearching) {
        [_searchBar resignFirstResponder];
        [self setIsSearching:NO];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
    NSArray *array = [_cityDic objectForKey:[NSString stringWithFormat:@"%@", _names[indexPath.section]]];
    CityModel *model = array[indexPath.row];
    if (_block) {
        _block(model);
    }
}

//获取并返回首字母
- (NSString *)firstCharactor:(NSString *)aString {
    if (aString.length == 0) {
        return nil;
    }
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //转换为带声调的拼音
    CFStringTransform((__bridge CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //转换为不带声调的拼音
    CFStringTransform((__bridge CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    return [pinYin substringToIndex:1];
}

//获取并返回首字母
- (NSString *)transformToPinyin:(NSString *)aString {
    NSMutableString *mutableString = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
    mutableString = (NSMutableString *)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
    [mutableString stringByReplacingOccurrencesOfString:@"'" withString:@""];
    NSString *pinYin = [mutableString capitalizedString];
    return [pinYin substringToIndex:1];
}


- (void)sonThread {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *pathCity = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
        NSString *strCity = [NSString stringWithContentsOfFile:pathCity encoding:NSUTF8StringEncoding error:nil];
        NSData *dataCity = [strCity dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dicCity = [NSJSONSerialization JSONObjectWithData:dataCity options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *result = [NSMutableArray array];
        for (NSDictionary *dic in [dicCity objectForKey:@"RECORDS"]) {
            CityModel *model = [[CityModel alloc] initWithDictionary:dic];
            NSString *str = [model.cityname substringToIndex:1];
            if ([str isEqualToString:@"市"] || [str isEqualToString:@"县"]) {
                continue;
            }
            NSString *pinyin = [self transformToPinyin:str];
            if ([_cityDic objectForKey:pinyin]) {
                if ([str isEqualToString:@"长"]) {
                    NSMutableArray *array = [_cityDic objectForKey:@"C"];
                    [array addObject:model];
                } else {
                    NSMutableArray *array = [_cityDic objectForKey:pinyin];
                    [array addObject:model];
                }
            } else {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:model];
                [_cityDic setObject:array forKey:pinyin];
                [result addObject:pinyin];
            }
        }
        
        NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
        NSWidthInsensitiveSearch | NSForcedOrderingSearch;
        NSComparator sort = ^(NSString *obj1,NSString *obj2){
            NSRange range = NSMakeRange(0,obj1.length);
            return [obj1 compare:obj2 options:comparisonOptions range:range];
        };
        [_names addObjectsFromArray:[result sortedArrayUsingComparator:sort]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self initView];
        });
        _tempArray = [NSMutableArray arrayWithArray:_names];
        _tempDic = [NSMutableDictionary dictionaryWithDictionary:_cityDic];
    });
}

- (void)initView {
    _addressView = [[AddressView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 20, (self.view.frame.size.height - 420) / 2, 20, 420) names:_names];
    [self.view addSubview:_addressView];
    _addressView.delegate = self;
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width - 20, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
}

- (void)addLocalHeader {
    UIView *local = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)];
    _name = [[UILabel alloc] initWithFrame:CGRectMake(13, 25, 140, 20)];
    [local addSubview:_name];
    [_name sizeToFit];
    
    _label = [[UILabel alloc] initWithFrame:CGRectMake(_name.frame.origin.x + _name.frame.size.width + 20, 0, 100, 70)];
    _label.text = @"GPS定位";
    _label.textColor = [UIColor colorWithRed:120 / 255.0 green:120 / 255.0 blue:120 / 255.0 alpha:1];
    [local addSubview:_label];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLocal:)];
    [local addGestureRecognizer:tap];
    _tableView.tableHeaderView = local;
    [_tableView reloadData];
}

- (void)tapLocal:(UIGestureRecognizer *)gestureRecognizer {
        CityModel *model = [[CityModel alloc] init];
        model.citycode = @0;
        _block(model);
        [self.navigationController popViewControllerAnimated:YES];
}


- (void)addressView:(AddressView *)addressView didSelectNum:(NSInteger)number {
    if (_names.count <= number || number <= -1) {
        return;
    }
    NSArray *array = [_cityDic objectForKey:[NSString stringWithFormat:@"%@", _names[number]]];
    if (array.count > 0) {
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:number] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
